"use client";
import { useRef, useState } from "react";
import styles from "./uploadObs.module.scss";
import upload from "./upload";

interface UploadObsProps {
  usetype?: string;
  showFileList?: boolean;
  callback?: (file: {
    name: string;
    size: number;
    type: string;
    url: string;
    raw: File;
  }) => void;
}

const UploadObs = ({
  usetype,
  callback,
  showFileList = true,
}: UploadObsProps) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [fileList, setFileList] = useState<File[]>([]);

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 B";
    const k = 1024;
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
  };

  // 删除文件
  const removeFile = (fileName: string) => {
    setFileList(fileList.filter((file) => file.name !== fileName));
  };

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      console.log("选择的文件:", file);
      // 调用上传函数
      const result = await upload({
        name: file.name,
        size: file.size,
        type: file.type,
        raw: file, // 这就是原始文件对象
      });
      console.log("上传结果:", result);
      setFileList([...fileList, file]);
      callback?.({
        name: file.name,
        size: file.size,
        type: file.type,
        raw: file,
        url: result?.url || "",
      });
    }
  };

  const handleButtonClick = () => {
    fileInputRef.current?.click(); // 触发文件选择
  };

  return (
    <div
      className={
        usetype === "dialog" ? styles.uploadObsDialog : styles.uploadObs
      }
    >
      <input
        ref={fileInputRef}
        type="file"
        className={styles.hiddenInput}
        onChange={handleFileSelect}
      />
      <button className={styles.customButton} onClick={handleButtonClick}>
        选择文件上传
      </button>
      {showFileList && fileList.length > 0 && (
        <div className={styles.uploadResult}>
          {fileList.map((file) => (
            <div key={file.name} className={styles.uploadResultItem}>
              <div className={styles.fileInfo}>
                <div className={styles.fileIcon}>📄</div>
                <div className={styles.fileName}>{file.name}</div>
              </div>
              <div className={styles.fileActions}>
                <span className={styles.fileSize}>
                  {formatFileSize(file.size)}
                </span>
                <button
                  className={styles.deleteBtn}
                  onClick={() => removeFile(file.name)}
                >
                  删除
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};
export default UploadObs;
